# @File    : catch_exception.py
# @Project : JBL_Android&iOS
from airtest.core.api import *
from common.logUtil import warning_a
from common.operate import OperateUtil


class ExceptionUtil:

    using = "^使用中.*"
    earbud = "^耳机：.*$"
    case = "^充电盒：.*$"

    def __init__(self, poco):
        self.poco = poco
        self.operate = OperateUtil()
        # 获取屏幕宽和高
        self.width = self.poco.get_screen_size()[0]
        self.height = self.poco.get_screen_size()[1]

    # 升级失败检测
    def check_fail(self):
        if self.poco("蓝牙开启。").exists():
            warning_a("耳机升级后未回连耳机,请将手动连接耳机后重试!")
            # 下拉状态栏
            self.operate.swipe_down()
            # 回连耳机
            self.poco(name="miui.systemui.plugin:id/expand_indicator", desc="展开").click()
            self.poco(text="JBL Live Flex 3").click()
            earbud = self.poco(textMatches=f"{self.using}").wait(20)
            if earbud.exists():
                touch(v=(540, 2060))
                sleep(2)
                # 上拉状态栏
                swipe((840, 2200), (840, 1330))
                # app回连耳机后检查耳机版本
                return self.check_version()
        elif self.poco("蓝牙已连接。").exists():
            warning_a("安装最后一分钟时更新失败")
            # 下拉状态栏
            self.operate.swipe_down()
            # 关闭蓝牙,断开耳机连接
            self.poco("已连接到蓝牙。").click()
            sleep(2)
            # 重新打开蓝牙,回连耳机
            self.poco("蓝牙,开启,未连接。").click()
            sleep(4)
            # 上拉状态栏
            self.operate.swipe_up()
            # app回连耳机后检查耳机版本
            return self.check_version()

    def check_version(self):
        other = self.poco(text="Others").wait(25)
        if other.exists():
            other.click()
            swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
            self.poco(text="支持").click()
            version = self.poco(textMatches=f"{self.case}")
            return version.get_text()[6:]
